<template>
    <show-modal :title="options.title" :loading="options.loading" width="440px" @cancel="cancel" @submit="submit">
        <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout">
            <a-form-item label="角色名称" name="name">
                <a-input v-model:value="formState.name" placeholder="请填写部门名称" />
            </a-form-item>
            <a-form-item label="角色编码" name="code">
                <a-input v-model:value="formState.code" :disabled="formState.id ? true : false" placeholder="请填写部门编码" />
            </a-form-item>
            <a-form-item label="角色权限" name="permission">
                <RouterTree :routes="formState.permission" @change="changeRoutes" />
            </a-form-item>
        </a-form>
    </show-modal>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import { rules } from './rules'
import { add, update } from '@/api/system/role';
import { message } from 'ant-design-vue';
import { useForm } from '@/hooks/use-form/index'
import { IRole } from '../role.type';
import RouterTree from '@/components/router-tree/index.vue'
import { deepClone } from '@/utils';

let props = defineProps({
    info: {
        type: Object,
        default: () => null
    }
})
let emit = defineEmits(['cancel', 'submit']);
// /**基本配置 */
const options = reactive({
    title: '角色信息',
    loading: false
})
/**表单 */
let form = reactive<IRole>({
    name: '',
    code: '',
    permission:[],
    status: true,
});
if(props.info && props.info.id){
    props.info.permission = props.info.permission?JSON.parse(props.info.permission):[]
    Object.assign(form, props.info)
}
const { formRef, layout, formState, showLoading, hideLoading, formValidateFields } = useForm(form)
// 提交
const submit = async () => {
    try {
        let res = await formValidateFields();
        let result = deepClone(res)
        result.permission = JSON.stringify(result.permission)
        showLoading()
        if (result.id) {
            await update(result);
        } else {
            await add(result);
        }
        message.success('操作成功');
        emit('submit');
    } finally {
        hideLoading()
    }
}
//取消
const cancel = () => {
    emit('cancel')
}
//选择权限
const changeRoutes = (e: any)=>{
    formState.value.permission = e;
}
</script>